package ipaintplugin.objects;

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.widgets.Display;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

public abstract class Figure implements IPmlable, Cloneable {

	// protected static final Display display = new Display();

	private int lineWidth = 1;
	private Color lineColor = getColor(SWT.COLOR_BLACK);// =
	// display.getSystemColor(SWT.COLOR_BLACK);
	private String lineColorString = "#000000";

	protected Figure() {
	}

	public int getLineWidth() {
		return lineWidth;
	}

	public void setLineWidth(int lineWidth) {
		this.lineWidth = lineWidth;
	}

	public Color getLineColor() {
		return lineColor;
	}

	public void setLineColor(Color lineColor) {
		this.lineColor = lineColor;
	}

	public void draw(GC canvas) {
		canvas.setForeground(lineColor);
		canvas.setLineWidth(lineWidth);
	}

	public abstract String getTagName();

	public abstract Object clone();

	@Override
	public void fromXML(Node el) {
		lineWidth = Integer.parseInt(el.getAttributes().getNamedItem(
				"lineWidth").getNodeValue());
		lineColorString = el.getAttributes().getNamedItem("lineColor")
				.getNodeValue();

		lineColor = getRGBColor(lineColorString);

	}

	@Override
	public void toXML(Document doc, Element el) {
		el.setAttribute("lineWidth", String.valueOf(lineWidth));
		el.setAttribute("lineColor", lineColorString);
	}

	public static final Color getRGBColor(String rgb) {
		if (rgb != null) {
			if(rgb.startsWith("#"))
				rgb = rgb.substring(1);
			int hex = Integer.parseInt(rgb, 16);
			int red = (0xff0000 & hex) >> 16;
			int green = (0x00ff00 & hex) >> 8;
			int blue = 0x0000ff & hex;
			return new Color(Display.getCurrent(), red, green, blue);
		} else {
			return getColor(SWT.COLOR_WHITE);
		}
	}

	public static final Color getColor(int systemColor) {
		return Display.getCurrent().getSystemColor(systemColor);
	}

}
